<template>
  <div>
    <el-dialog
      :visible.sync="courseDialogVisible"
      :before-close="handleClose"
      title="添加活动课程"
      width="50%"
    >
      <el-steps
        :active="stepsActive"
        class="stepsBox"
        finish-status="success"
        simple
        style="width:100%;height:50px;"
      >
        <el-step title="选择参与活动的课程"/>
        <el-step title="设置活动课程分成比例"/>
      </el-steps>
      <div v-show="stepsActive === 1">
        <div class="setpsOne-titleTop">
          <div>参与活动课程</div>
          <i class="el-icon-question"></i>
        </div>
        <div class="setpsOne-titleNav">
          <el-button type="primary" style="margin-bottom: 20px;" @click="addSelectCourse()">自定义添加课程</el-button>
        </div>
        <el-table
          :data="dialogTableData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
          border
          style="width: 100%;margin-top:20px;max-height:310px;overflow:auto;"
        >
          <el-table-column prop="courseName" label="名称" width="400" align="center"/>
          <el-table-column prop="price" label="商品价格" min-width="10" align="center"/>
          <el-table-column prop="dialogManage" label="操作" min-width="10" align="center">
            <template slot-scope="scope">
              <el-button size="small" @click="removeBtn(scope.$index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="stepsActive === 2">
        <div class="setpsTwo-titleTop">
          <div>
            共选择{{ dialogTableData.length }}门课程，设置代理商统一分成比例：通过代理商推广的课程产生的每笔消费，代理商可获
            <span
              style="color:#63B8FF"
            >订单价格</span>的
            <el-input v-model="rateAll" style="width:60px" @blur="setRateAll"/>
            %分成
            <i class="el-icon-question"></i>
          </div>
        </div>
        <el-table
          :data="dialogTableData"
          border
          style="width: 100%;margin-top:20px;max-height:330px;overflow:auto;"
        >
          <el-table-column prop="courseName" label="名称" width="400" align="center"/>
          <el-table-column prop="price" label="商品价格" min-width="10" align="center"/>
          <el-table-column label="代理商分成比例" min-width="10" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rate" style="width:60px;"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog
        :visible.sync="selectCourseDialog"
        class="innerDialog"
        :before-close="closeSelectCourseDialog"
        append-to-body
        title="自定义添加课程"
        width="48%"
      >
        <div style="margin-bottom:10px;">
          <el-input v-model="searchKeyWord" style="width:200px;"/>
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button size="medium" type="info" @click="clearParams">清空</el-button>
        </div>
        <el-table
          ref="multipleTable"
          :data="newourseTable"
          :row-key="getRowKeys"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column :reserve-selection="true" type="selection" align="center" width="55"/>
          <el-table-column property="title" label="商品名称" align="center"/>
          <el-table-column property="price" label="商品价格" align="center"/>
        </el-table>
        <!--分页-->
        <div style="margin:20px 0;">
          <el-pagination
            :page-size="innerpagesize"
            :total="courseTable.length"
            background
            layout="prev, pager, next"
            @current-change="innerCurrentChange"
          />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeSelectCourseDialog">取 消</el-button>
          <el-button type="primary" @click="addAllCourse()">确 定</el-button>
        </span>
      </el-dialog>
      <el-pagination
        v-if="stepsActive === 1"
        :total="total"
        :current-page.sync="currentpage"
        :page-size="pagesize"
        :page-sizes="[3, 5,]"
        background
        layout="sizes, prev, pager, next"
        style="margin-top:20px;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <span slot="footer" class="dialog-footer">
        <el-button v-if="stepsActive === 1" style="float:left" @click="allRemove">全部移除</el-button>
        <el-button v-if="stepsActive === 1" type="primary" @click="nextStep">下一步</el-button>
        <el-button
          v-if="stepsActive === 2"
          type="primary"
          style="float:left"
          @click="againRatio"
        >重新设置比例</el-button>
        <el-button v-if="stepsActive === 2" @click="lastStep">上一步</el-button>
        <el-button v-if="stepsActive === 2" type="primary" @click="confirmBtn">完成</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {getCourseNotInActivity} from '@/api/distribution/agencyOverAllSet'
  import {getTenantId, getUserName} from '@/utils/auth'
  import {courseList} from '@/api/user/user' // 数据接口

  export default {
    props: {
      data: {
        type: Object,
        default() {
          return {}
        }
      }
    },
    data() {
      return {
        stepsActive: 1,
        dialogVisible: false,
        selectCourseDialog: false,
        rateAll: '',
        EduUserVo: {},
        tableValue: false,
        dialogTableData: [],
        total: 0,
        currentpage: 1,
        pagesize: 5,
        courseTable: [],
        filterData: [],
        searchKeyWord: '',
        innercurrent: 1,
        innerpagesize: 5,
        multipleSelectionAll: [], // 所有选中的数据包含跨页数据
        multipleSelection: [], // 当前页选中的数据
        idKey: 'id',
        // 获取row的key值
        getRowKeys(row) {
          return row.id
        },
        selectIds: [],
        noSelectIds: []
      }
    },
    computed: {
      courseDialogVisible() {
        return this.data.dialog
      },
      newourseTable() {
        return this.courseTable.slice((this.innercurrent - 1) * this.innerpagesize, this.innercurrent * this.innerpagesize)
      }
    },
    created() {
      this.getCourseListData()
    },
    methods: {
      closeSelectCourseDialog() {
        this.multipleSelectionAll = [];
        this.multipleSelection = [];
        this.selectIds = [];
        this.noSelectIds = [];
        //清除选中状态
        this.$refs.multipleTable.clearSelection();
        this.selectCourseDialog = false;
      },
      // 关闭按钮
      handleClose() {
        this.$emit('closed');
        this.allRemove()
      },
      getCourseListData() {
        this.EduUserVo.tenantId = getTenantId();
        courseList(this.EduUserVo).then(res => {
          this.courseTable = res.data.items
          this.filterData = res.data.items;
          this.total = res.data.items.length
        })
      }
      ,
      addAllCourse() {
        this.selectCourseDialog = false;
        this.getAllSelectionData();
        getCourseNotInActivity(this.selectIds.join(',')).then(res => {
          this.dialogTableData = res.data.items
        })
      },
      addSelectCourse() {
        this.selectCourseDialog = true
      },
      // 表格移除按钮事件
      removeBtn(index) {
        this.dialogTableData.splice(index, 1)
      },
      // 全部移除按钮事件
      allRemove() {
        this.dialogTableData = []
      },
      // 下一步按钮跳转
      nextStep() {
        this.stepsActive = 2
      },
      // 上一步按钮跳转
      lastStep() {
        this.stepsActive = 1
      },
      // 重新设置比例时间
      againRatio() {
        this.rateAll = '';
        this.dialogTableData.map(item => {
          item.rate = ''
        })
      },
      setRateAll() {
        this.dialogTableData.map(item => {
          item.rate = this.rateAll;
          item.creator = getUserName();
          item.tenantId = getTenantId()
        })
      },
      // 完成按钮事件
      confirmBtn() {

        this.dialogTableData.map(item => {
          if (!item.rate) {
            item.rate = this.rateAll
          }
          item.creator = getUserName();
          item.tenantId = getTenantId()
        });

        this.$emit('confirm', this.dialogTableData);
        this.allRemove();
        this.stepsActive = 1;
        this.rateAll = ''
      },
      handleSizeChange(val) {
        this.currentpage = 1;
        this.pagesize = val;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        this.currentpage = val;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleSearchCourse(val) {
        // 待处理
        console.log(val)
      },
      // 设置选中的方法
      setSelectRow() {
        if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) {
          return
        }
        // 标识当前行的唯一键的名称
        const idKey = this.idKey;
        const selectAllIds = [];
        this.multipleSelectionAll.forEach(row => {
          selectAllIds.push(row[idKey])
        });
        this.$refs.multipleTable.clearSelection();
        for (let i = 0; i < this.newourseTable.length; i++) {
          if (selectAllIds.indexOf(this.newourseTable[i][idKey]) >= 0) {
            // 设置选中，记住table组件需要使用ref="table"
            this.$refs.multipleTable.toggleRowSelection(this.newourseTable[i], true)
          }
        }
      },
      // 记忆选择核心方法
      changePageCoreRecordData() {
        // 标识当前行的唯一键的名称
        const idKey = this.idKey;
        const that = this;
        // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
        if (this.multipleSelectionAll.length <= 0) {
          this.multipleSelectionAll = this.multipleSelection
          // return
        }
        // 总选择里面的key集合
        const selectAllIds = [];
        this.multipleSelectionAll.forEach(row => {
          selectAllIds.push(row[idKey])
        });
        // 获取当前页选中的id
        this.multipleSelection.forEach(row => {
          this.selectIds.push(row[idKey]);
          // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
          if (selectAllIds.indexOf(row[idKey]) < 0) {
            that.multipleSelectionAll.push(row)
          }
        });

        console.log('选中的课程ID:' + this.selectIds);
        // 得到当前页没有选中的id
        this.newourseTable.forEach(row => {
          if (this.selectIds.indexOf(row[idKey]) < 0) {
            this.noSelectIds.push(row[idKey])
          }
        });
        this.noSelectIds.forEach(id => {
          if (selectAllIds.indexOf(id) >= 0) {
            for (let i = 0; i < that.multipleSelectionAll.length; i++) {
              if (that.multipleSelectionAll[i][idKey] === id) {
                // 如果总选择中有未被选中的，那么就删除这条
                that.multipleSelectionAll.splice(i, 1);
                break
              }
            }
          }
        });

        console.log('没选中的课程ID:' + this.noSelectIds)
      },
      innerCurrentChange(val) {
        // 改变页的时候调用一次
        this.changePageCoreRecordData();
        this.innercurrent = val;
        // this.query()
        this.setSelectRow()
      },
      handleSelectionChange(val) {
        // table组件选中事件,记得加上@selection-change="handleSelectionChange"
        this.multipleSelection = val;
        console.log(this.multipleSelection)
      },
      // 得到选中的所有数据
      getAllSelectionData() {
        // 再执行一次记忆勾选数据匹配，目的是为了在当前页操作勾选后直接获取选中数据
        this.changePageCoreRecordData()
      },
      handleFilter() {
        this.courseTable = this.filterData.filter(item => {
          if (item.title.toLocaleLowerCase().indexOf(this.searchKeyWord.toLocaleLowerCase()) < 0) return false;
          return true
        });
        this.total = this.courseTable.length
      },
      clearParams() {
        this.searchKeyWord = '';
        this.getCourseListData()
      },
    }

  }
</script>
<style lang="scss" scoped>
  .setpsOne-titleTop {
    margin-top: 20px;
    font-size: 16px;

    div {
      display: inline-block;
    }

    i {
      display: inline-block;
    }
  }

  .setpsOne-titleNav {
    margin-top: 20px;

    button {
      float: right;
    }
  }

  .setpsTwo-titleTop {
    margin-top: 20px;
    font-size: 16px;

    div {
      display: inline-block;
    }

    i {
      display: inline-block;
    }
  }

  .innerDialog {
    /deep/ .el-dialog__body {
      padding: 20px 20px;
    }
  }
</style>

